/*
 * IBM Corporation.
 * Copyright (c) 2014 All Rights Reserved.
 */

package com.ibm.iisp.datamanager.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.persistence.TypedQuery;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ibm.iisp.common.util.FileStoreUtils;
import com.ibm.iisp.common.vo.PagedQueryResult;
import com.ibm.iisp.data.model.DataTable;
import com.ibm.iisp.data.model.DataTableColumn;
import com.ibm.iisp.data.service.DataCommonService;
import com.ibm.iisp.datamanager.vo.DataTableQueryParam;

/**
 * 类作用：
 * @author Johnny@cn.ibm.com
 * 使用说明：
 */
@Service
@Transactional(readOnly = true)
public class DataManagerServiceImpl extends DataCommonService implements DataManagerService {
	public final static String DATA_IN_DATE_PROCESS_ID = "DataInputTimeProcess";

	@Inject
	FileStoreUtils fileStoreUtils;
	public static final String TEMPATE_ROOT = "/iisp-data-input-date";

	/* (non-Javadoc)
	 * @see com.ibm.iisp.datamanager.service.DataManagerService#getDataTables(java.lang.String)
	 */
	@Override
	public List<DataTable> getDataTables(String tableCode) {
		if (tableCode == null || tableCode.length() == 0) {
			TypedQuery<DataTable> qry = dao.createNamedQuery(DataTable.QUERY_GET_ALL, DataTable.class);
			List<DataTable> tbs = qry.getResultList();
			return tbs;
		}
		TypedQuery<DataTable> qry = dao.createNamedQuery(DataTable.QUERY_BY_NAME, DataTable.class);
		qry.setParameter("tableName", "%" + tableCode.toUpperCase() + "%");
		List<DataTable> tbs = qry.getResultList();
		return tbs;
	}


	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	@Override
	public PagedQueryResult<?> getTableData(DataTableQueryParam param) {
		DataTable dataTable = dao.find(DataTable.class, param.getTableCode());
		StringBuilder sb = new StringBuilder("select ");
		StringBuilder sbOrder = new StringBuilder();

		for (int i = 0; i < dataTable.getColumns().size(); i++) {
			if (i > 0) {
				sb.append(",");
			}
			DataTableColumn col = dataTable.getColumns().get(i);
			sb.append(col.getCode());
			if (!StringUtils.isEmpty(col.getSortDirect())) {
				if (sbOrder.length() > 1) {
					sbOrder.append(",");
				}
				sbOrder.append(col.getCode()).append(" ").append(col.getSortDirect());
			}
		}
		sb.append(" from ").append(dataTable.getCode()).append(" ");
		if (param.getParams() != null) {
			for (Map.Entry<String, Object> f : param.getParams().entrySet()) {
				String name = f.getKey();
				DataTableColumn col = getDataTableColumn(dataTable, name);
				if (col != null && StringUtils.isNotEmpty(f.getValue().toString())) {
					if (sb.indexOf(" where") > 0) {
						sb.append(" and ");
					} else {
						sb.append(" where ");
					}
					if ("date".equals(col.getDataType())) {
						Date d = new Date(Long.valueOf(f.getValue().toString()));
						String val = df.format(d);
						sb.append(name).append(" = ").append("to_date( '").append(val).append("','yyyy-MM-dd HH:mi')");
					} else if ("number".equals(col.getDataType())) {
						sb.append(name).append(" = ").append(f.getValue());
					} else {
						String val = f.getValue().toString();
						if (val.indexOf("%") >= 0) {
							sb.append("upper(").append(name).append(") like '").append(val.toUpperCase()).append("'");
						} else {
							sb.append(name).append(" = '").append(f.getValue()).append("'");
						}
					}
				}
			}
		}
		if (sbOrder.length() > 1) {
			sb.append(" order by ").append(sbOrder);
		}
		return null;// dao.executePagedQuery(param, sb.toString());
	}

	DataTableColumn getDataTableColumn(DataTable dataTable, String colName) {
		for (DataTableColumn col : dataTable.getColumns()) {
			if (col.getCode().equals(colName) && Boolean.TRUE.equals(col.getIsFilter())) {
				return col;
			}
		}
		return null;
	}


}
